package com.css.dzj.dzjdzqs.common.config;

import com.alibaba.fastjson.JSON;
import com.css.dzj.dzjdzqs.common.util.R;
import com.css.dzj.dzjdzqs.sys.user.entity.LoginUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 拦截逻辑
 *
 * @author liangXG
 */
@PropertySource(value = "classpath:base.properties")
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${PERMISSION_EXCLUDE_PATH}")
    private String PERMISSION_EXCLUDE_PATH;

    ObjectMapper json = new ObjectMapper();
    @Value("${MAIN_WORK_URL}")
    private String MAIN_WORK_URL;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String infoKey = "";
        //获取cookie中存取的值
        Cookie[] cookies=request.getCookies();
        //判断是否cookie生成
        if(cookies==null||cookies.length==0){
            response.sendRedirect(MAIN_WORK_URL + "/html/login.html");
            return false;
        }else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("userInfo")) {
                    infoKey = cookie.getValue();
                }
            }
        }
        //根据cookie中获取的value在redis缓存中查询用户信息
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        String userInfo = JSON.toJSONString(vo.get(infoKey));
        if (userInfo.isEmpty() || userInfo.equals("null")) {
            response.sendRedirect(MAIN_WORK_URL + "/html/login.html");
            return false;
        }
        //判断是否session中有用户信息，如果没有将用户信息存入session中
        HttpSession loginSession = request.getSession();
        if (loginSession == null || (loginSession.getAttribute("_USER_LOGIN_INFO_") == null)) {
            LoginUser lu = JSON.parseObject(userInfo, LoginUser.class);
            //base验证用户是否登录需要两个TOKEN
            loginSession.setAttribute("accessToken", lu.getAccessToken());
            loginSession.setAttribute("refreshToken", lu.getRefreshToken());
            loginSession.setAttribute("userId", lu.getUserId());
            loginSession.setAttribute("loginName", lu.getLoginName());
            loginSession.setAttribute("_USER_LOGIN_INFO_", lu);
        }
        //权限白名单，不配置权限也不会被拦截的请求放到这里
        String[] permission_exclude_path = PERMISSION_EXCLUDE_PATH.split(",");
        //当前request请求
        String reqFunc = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        if (Arrays.asList(permission_exclude_path).contains(reqFunc)) {
            return true;
        }

        /*
                List permission = null;
                LoginUser userInfo = (LoginUser) loginSession.getAttribute("_USER_LOGIN_INFO_");
                if(userInfo != null){
                    permission = userInfo.getPermission();
                }
        */

        /*if(permission != null && permission.contains(reqFunc)){
            return true;
        }else{
            return returnErrorInfo(response, "权限不足，无法查看");
        }*/
        return true;
    }

    private boolean returnErrorInfo(HttpServletResponse response, String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //权限判断
        json.writeValue(response.getOutputStream(), R.error(500, msg));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
